package com.hxd.otc.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.module.coin_deal.bean.CoinBottomDialogBean;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.EncryptUtils;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.LimitNumberTextWatcher;

/**
 * 包  名 :  com.hxd.otc.dialog
 * 类  名 :  CoinDealBottomDialog
 * 作  者 :  胡庆岭
 * 时  间 :  2018/7/10 10:50
 * 描  述 :  ${币币交易底部dialog}
 */
public class CoinDealBottomDialog extends Dialog {
    private CoinBottomDialogBean mDialogBean;
    private TextView mTitleText;
    private TextView mPriceText;
    private TextView mCountText;
    private TextView mMoneyText;
    private TextView mStatusText;
    private TextView mCancelText;
    private TextView mSureText;
    private EditText mCountEdit;
    private TextView tvCoinType;
    private EditText mPasswordEdit;
    private static final int HANDLER_WHAT = 100;
    private int mTime = 60;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    private OnItemClickListener onItemClickListener;
    private Handler mHandler;

    public CoinDealBottomDialog(@NonNull Context context, CoinBottomDialogBean bean) {
        this(context, R.style.DialogStyle);
        this.mDialogBean = DataUtils.checkNull(bean);
        init();
    }

    public CoinDealBottomDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);

    }

    private void init() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setCanceledOnTouchOutside(true);
        setContentView(R.layout.weight_coin_deal_bottom_dialog);
        initView();
        initData();
        initEvent();
        initWindows();
    }


    private void initView() {
        mTitleText = findViewById(R.id.tv_title);
        mPriceText = findViewById(R.id.tv_price);
        mCountText = findViewById(R.id.count_tv);
        mMoneyText = findViewById(R.id.money_tv);
        mStatusText = findViewById(R.id.all_tv);
        mCancelText = findViewById(R.id.tv_cancel);
        mSureText = findViewById(R.id.tv_sure);
        mCountEdit = findViewById(R.id.et_virtual_count);
        mPasswordEdit = findViewById(R.id.et_password);
        tvCoinType = findViewById(R.id.tv_virtual_type);

    }

    private void initData() {
        refreshView();
    }

    private void initHandler() {
        if (mHandler == null) {
            mTime = 60;
            mHandler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    switch (msg.what) {
                        case HANDLER_WHAT:
                            mTime--;
                            if (mTime > 0) {
                                mHandler.sendEmptyMessageDelayed(HANDLER_WHAT, 1000);
                                mCancelText.setText(getContext().getString(R.string.cancel_millis, String.valueOf(mTime)));
                            } else {
                                mCancelText.setText(R.string.cancel);
                                dismiss();
                            }
                            break;
                    }
                    return true;
                }
            });
            mHandler.sendEmptyMessageDelayed(HANDLER_WHAT, 1000);
        }
    }

    private void refreshView() {
        mCountEdit.setText("");
        mPasswordEdit.setText("");
        mMoneyText.setText(UIUtils.getContext().getString(R.string.two_placeholder_money,
                StringUtil.format6Number(DataUtils.mul(mDialogBean.money, 0)), mDialogBean.moneyUnit));

        initHandler();

        mCancelText.setText(getContext().getString(R.string.cancel_millis, String.valueOf(mTime)));
        mTitleText.setText(mDialogBean.title);
        mPriceText.setText(mDialogBean.price);
        mCountText.setText(mDialogBean.count);
        tvCoinType.setText(mDialogBean.numberUnit);

        switch (mDialogBean.typeDeal) {
            case Constant.Deal.TYPE_BUY:
                mStatusText.setTextColor(ContextCompat.getColor(getContext(), R.color.color_FF5AC792));
                mStatusText.setText(R.string.all_buy);
                break;
            case Constant.Deal.TYPE_SELL:
                mStatusText.setTextColor(ContextCompat.getColor(getContext(), R.color.color_FFFF7766));
                mStatusText.setText(R.string.all_sell);
                break;
        }
    }

    private void initEvent() {
        mCancelText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mSureText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String count = mCountEdit.getText().toString().trim();
                if (DataUtils.isEmpty(count)) {
                    BlocksToast.get().showToast(R.string.please_enter_the_number_of_transactions);
                    return;
                } else if (Double.valueOf(count) > mDialogBean.maxCount) {
                    BlocksToast.get().showToast(R.string.over_trade_deal);
                    return;
                }
                String password = mPasswordEdit.getText().toString().trim();
                if (DataUtils.isPayPassword(password)) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onSure(v, count, EncryptUtils.getSHA256(password));
                    }
                    dismiss();
                }

            }
        });
        mStatusText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCountEdit.setText(String.valueOf(mDialogBean.maxCount));
                mCountEdit.setSelection(mCountEdit.getText().toString().trim().length());
            }
        });
        mCountEdit.addTextChangedListener(new LimitNumberTextWatcher(mCountEdit, 9, 4) {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                //如果只有小数点，补全成0.
                if (s.toString().trim().equalsIgnoreCase(".")) {
                    mCountEdit.setText("0.");
                    mCountEdit.setSelection(mCountEdit.getText().toString().length());
                    return;
                }
                if (s.toString().trim().length() > 0) {
                    mMoneyText.setText(UIUtils.getContext().getString(R.string.two_placeholder_money,
                            StringUtil.format6Number(DataUtils.mul(mDialogBean.money, Double.valueOf(s.toString()))), mDialogBean.moneyUnit));
                } else {
                    mMoneyText.setText(UIUtils.getContext().getString(R.string.two_placeholder_money,
                            StringUtil.format6Number(DataUtils.mul(mDialogBean.money, 0)), mDialogBean.moneyUnit));
                }
            }
        });
    }

    private void initWindows() {
        Window window = getWindow();
        if (window != null) {
            DisplayMetrics dm = new DisplayMetrics();
            window.getWindowManager().getDefaultDisplay().getMetrics(dm);
            WindowManager.LayoutParams windowAttributes = window.getAttributes();
            windowAttributes.width = WindowManager.LayoutParams.MATCH_PARENT;
            windowAttributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
            windowAttributes.gravity = Gravity.BOTTOM;
            window.setAttributes(windowAttributes);
        }
    }

    private void destroyHandler() {
        if (mHandler != null) {
            mHandler.removeMessages(HANDLER_WHAT);
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    public void setData(CoinBottomDialogBean data) {
        this.mDialogBean = data;
        refreshView();
    }

    public interface OnItemClickListener {
        void onSure(View v, String dealCount, String password);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        destroyHandler();

    }
}
